#!/user/bin/env python
# -*- coding: utf-8 -*-
from controls.data_topic_note_mysql import TopicNoteItem

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, Boolean, TIMESTAMP
from sqlalchemy.sql import func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

""" topic_img_item collection has
    id:             自增id（int）
    userid:         用户id（int）
    noteid:         内容id（int）
    ctime:          添加时间（datetime）
"""

class TopicNoteLikeItem(object):
    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['noteid'] = self.noteid
        res['ctime'] = ''
        if self.ctime:
            res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")
        return res

    def __repr__(self):
        return "%d" % (self.imgid)


topic_note_like_table = Table(
    'topic_note_like', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('userid', Integer, nullable=False),
    Column('noteid', Integer, index=True, nullable=False),
    Column('ctime', TIMESTAMP, server_default=func.now()),
)

mapper(TopicNoteLikeItem, topic_note_like_table)


def create_topic_note_like_table_if_not_exist():
    metadata.create_all(engine)


def add_topic_note_like_item(p_item):
    item = TopicNoteLikeItem()
    item.userid = p_item['userid']
    item.noteid = p_item['noteid']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_topic_note_like_by_noteid_and_userid(p_noteid, p_userid):
    try:
        session = Session()
        item = session.query(TopicNoteLikeItem) \
            .filter_by(noteid=p_noteid, userid=p_userid).first()

        res = item.to_dict() if item else None
        return res
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def del_topic_note_like_by_noteid_and_userid(p_noteid, p_userid):
    try:
        session = Session()
        session.query(TopicNoteLikeItem).filter_by(noteid=p_noteid, userid=p_userid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_note_like_count_by_noteid(p_noteid):
    try:
        session = Session()
        item = session.query(func.count(TopicNoteLikeItem.noteid)). \
            filter_by(noteid=p_noteid).first()
        return item[0] if item else 0
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

'''
def get_like_topic_note_id_by_userid(p_userid, offset=0):
    try:
        session = Session()
        res_list = session.query(TopicNoteLikeItem.noteid) \
            .filter_by(p_userid=p_userid, status=STATUS_LIKE) \
            .offset(offset).limit(20).all()

        return [res[0] for res in res_list]
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()

def get_topic_note_like_by_noteid_list(p_noteid_list):
    try:
        session = Session()



def update_topic_note_like_status(p_item):
    try:
        session = Session()
        session.query(TopicNoteLikeItem) \
            .filter_by(
            noteid=p_item['note_id'],
            userid=p_item['user_id']
        ).update({TopicNoteLikeItem.status: p_item['status']},
                 synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()

def get_topic_note_like_count_by_noteid(p_noteid_list):
    try:
        session = Session()
        res = session.query(TopicNoteLikeItem.noteid, func.count(TopicNoteLikeItem.id)). \
            filter(TopicNoteLikeItem.noteid.in_(p_noteid_list)).group_by(TopicNoteLikeItem.noteid).all()
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()
'''

def get_note_like_count_map_by_noteid_list(p_noteid_list):
    try:
        session = Session()
        items = session.query(TopicNoteLikeItem.noteid,
                              func.count(TopicNoteLikeItem))\
            .filter(TopicNoteLikeItem.noteid.in_(p_noteid_list))\
            .group_by(TopicNoteLikeItem.noteid).all()
        note_like_count_map = dict(items)
        return note_like_count_map
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_note_like_by_noteid_list_and_userid(p_noteid_list, p_userid):
    try:
        session = Session()
        items = session.query(TopicNoteLikeItem.noteid)\
            .filter(TopicNoteLikeItem.noteid.in_(p_noteid_list))\
            .filter(TopicNoteLikeItem.userid==p_userid).all()
        return [i[0] for i in items]
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_note_like_by_followed_userid(p_followed_userid, begin, limit):
    try:
        session = Session()

        items = session.query(TopicNoteLikeItem)\
            .join(TopicNoteItem, TopicNoteLikeItem.noteid == TopicNoteItem.noteid)\
            .filter(TopicNoteItem.userid == p_followed_userid)\
            .order_by(TopicNoteLikeItem.ctime.desc())\
            .offset(begin).limit(limit)\
            .all()
        return [i.to_dict() for i in items]
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_all_note_like():
    """
    在刷新脚本里使用，正式环境中尽量不要使用
    慎用！！！
    """
    try:
        session = Session()
        items = session.query(TopicNoteLikeItem).all()
        return [i.to_dict() for i in items]
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_topic_note_like_table_if_not_exist()
    c_item = {
        'userid': 1,
        'noteid': 1
    }
    add_topic_note_like_item(c_item)
